<?php

namespace App\Http\Controllers\Statistics;

use App\Helpers\ResponseData;
use App\Http\Controllers\Controller;
use App\Models\Car;
use App\Models\InsureLogs;
use App\Models\MarketExpense;
use App\Models\Order;
use App\Models\RevenueStatement;
use Illuminate\Pagination\LengthAwarePaginator;
use Modules\Car\Entities\CarOrder;
// use App\Models\User;
use Modules\Car\Entities\Customer;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Modules\Car\Entities\Illegal;
use Modules\Car\Entities\Insurance;
use Modules\Car\Entities\Maintenance;
use Modules\Car\Entities\Service;
use App\Models\Car\MortgageLog;
use App\Models\Order\LeaseChangeLog;
use Modules\Car\Entities\RecognizeDrivingLicense;
use App\Models\Car\ExternalTransfer;
class IncomeController extends Controller
{
    use ResponseData;
    public function getOrderSett(CarOrder $model,Request $request){
        $orderSett = $model
        ->whereIn('order_sn',$request->order_sns)
        ->where('status',6)
        ->whereIn('process_status',[3,4,5,6])
        ->select('id','order_sn', 'fact_pay', 'platform_fact_pay', 'over_time_fee','fetch_time','return_time')
        ->get();
        return $this->success($orderSett);
    }
    // 收入统计
    public function getIncome(CarOrder $model,Request $request){
        $startOfMonth = Carbon::now()->startOfMonth();
        $endOfMonth = Carbon::now()->endOfMonth();
        if($request->filled('search')){
            $search = $request->search;
            $model = $model->where(function($query)use($search){
                $query->where('phone','like','%'.$search.'%')
                    ->orWhere('wx_name','like','%'.$search.'%')
                    ->orWhere('source','like','%'.$search.'%')
                    ->orWhere('department','like'.'%'.$search.'%')
                    ->orWhere('nickname','like','%'.$search.'%')
                    ->orWhere('customer_name','like','%'.$search.'%')
                    ->orWhere('name','like','%'.$search.'%')
                    ->orWhere('plate_number','like','%'.$search.'%')
                    ->orWhere('license_number','like','%'.$search.'%')
                    ->orWhere('order_sn',$search);
            });
        }
        if($request->filled('is_three_platform')){
            $model = $model->where('platform_fact_pay','>',0);
        }
        if($request->filled('is_mendian')){
            $model = $model->where('fact_pay','>',0);
        }
        $size = $request->input('size',10);
        $model2 = clone $model;
        $model = $model
        ->where('status',6)
        ->whereIn('process_status',[4,5,6])
        ->with('renewLease', 'car')
        ->select('id','order_sn','activity_type','source','total','is_reconcile','additional_services_price','fact_pay_total','zujin_income','additional_income','services_income', 'is_reconciliation', 'over_time_fee','fact_pay', 'department', 'name', 'wx_name', 'lease_days', 'fetch_hours', 'pre_fetch_time', 'pre_return_time', 'platform_fact_pay', 'settle_status', 'all_handel_amount', 'fetch_time' ,'return_time', 'plate_number','diff_rate','change_price','settle_lease_price','is_reconciliation_time','ok_reconciliation_time', 'mini_phone','car_series_id','is_evidence');
        if($request->filled('department')){
            $model = $model->where('department',$request->department);
        }

        // 订单来源
        if($request->filled('order_source')){
            $model = $model->whereIn('source',$request->order_source);
        }
        // fact_return_over_at字段目前没用过，定义为操作结算的时间
        if($request->filled('start')&&$request->filled('end')){
            $model = $model->whereBetween('fact_return_over_at',[$request->start,$request->end]);
        }
        if($request->filled('is_start')&&$request->filled('is_end')){
            $model = $model->whereBetween('is_reconciliation_time',[$request->is_start,$request->is_end]);
        }
        if($request->filled('ok_start')&&$request->filled('ok_end')){
            $model = $model->whereBetween('ok_reconciliation_time',[$request->ok_start,$request->ok_end]);
        }
        if($request->filled('order_sns')){
            $model = $model->whereIn('order_sn',$request->order_sns);
        }
        // 常规、夜租、外调
        if($request->filled('activity_type')){
            $model = $model->where('activity_type',$request->activity_type);
            $model2 = $model2->where('activity_type',$request->activity_type);
            // 如果是外调类型
            if($request->activity_type==10){
                // ->select('order_sn','activity_type','source','zujin_income','is_reconcile','additional_services_price','fact_pay_total');
                $firstCollect = DB::table('external_transfers')
                    ->select(
                        DB::raw('id'),
                        DB::raw('order_sn'),
                        DB::raw('10 as activity_type'),
                        DB::raw('1 as source'),
                        DB::raw('50 as total'),
                        DB::raw('40 as is_reconcile'),
                        DB::raw('30 as additional_services_price'),
                        DB::raw('lease_price as fact_pay_total'),
                        DB::raw('90 as zujin_income'),
                        DB::raw('60 as additional_income'),
                        DB::raw('70 as services_income'),
                        DB::raw('is_reconciliation'),
                        DB::raw('0 as over_time_fee'),
                        DB::raw('profit_price as fact_pay'),
                        DB::raw('department'),
                        DB::raw('category as name'),
                        DB::raw('customer_name as wx_name'),
                        DB::raw('100 as lease_days'),
                        DB::raw('110 as fetch_hours'),
                        DB::raw('start_date as pre_fetch_time'),
                        DB::raw('end_date as pre_return_time'),
                        DB::raw('0 as platform_fact_pay'),
                        DB::raw('3 as settle_status'),
                        DB::raw('lease_price as all_handel_amount'),
                        DB::raw('sd_time as fetch_time'),
                        DB::raw('qh_time as return_time'),
                        DB::raw('plate_number'),
                        DB::raw('0 as diff_rate'),
                        DB::raw('0 as change_price'),
                        DB::raw('0 as settle_lease_price'),
                        DB::raw('is_reconciliation_time'),
                        DB::raw('ok_reconciliation_time'),
                        DB::raw('0 as car_series_id'),
                        DB::raw('0 as is_evidence'),
                    );
                if($request->filled('start')&&$request->filled('end')){
                    $firstCollect = $firstCollect->whereBetween('created_at',[$request->start,$request->end]);
                }
                if($request->filled('is_start')&&$request->filled('is_end')){
                    $firstCollect = $firstCollect->whereBetween('is_reconciliation_time',[$request->is_start,$request->is_end]);
                }
                if($request->filled('ok_start')&&$request->filled('ok_end')){
                    $firstCollect = $firstCollect->whereBetween('ok_reconciliation_time',[$request->ok_start,$request->ok_end]);
                }
                if($request->filled('departmentname')){
                    $firstCollect = $firstCollect->where('department',$request->departmentname);
                }
                if($request->filled('order_sns')){
                    $firstCollect = $firstCollect->whereIn('order_sn',$request->order_sns);
                }
                $model3 = clone $firstCollect;
                $model4 = clone $firstCollect;
                $model5 = clone $firstCollect;
                $ddz_total = $model3->where('is_reconciliation', 1)->sum('profit_price');
                $ddz_total1 = 0;
                $ddz_total2 = 0;
                $ddz_count = $model3->where('is_reconciliation', 1)->count();
                $ddz_count_month = $model3->where('is_reconciliation', 1)->whereBetween('updated_at', [$startOfMonth, $endOfMonth])->count();
                $drz_total = $model4->where('is_reconciliation', 2)->sum('profit_price');
                $drz_total1 = 0;
                $drz_total2 = 0;
                $drz_count = $model4->where('is_reconciliation', 2)->count();
                $yrz_total = $model5->where('is_reconciliation', 3)->sum('profit_price');
                $yrz_total1 = 0;
                $yrz_total2 = 0;
                $yrz_count = $model5->where('is_reconciliation', 3)->count();
                if($request->filled('is_reconciliation')){
                    $firstCollect = $firstCollect->whereIn('is_reconciliation',$request->is_reconciliation);
                }
                $data = $firstCollect->paginate($size);
                $month_order = 0;
                // 计算合并后的数据的总金额
                $amount_total = $firstCollect->sum('profit_price');
                // 超时费
                $chaoshi_total = 0;
                // 三方平台
                $sanfang_total = 0;
                // 租金
                $zujin_total1 = 0;
                $zujin_total2 = 0;
                return $this->success(compact('data','amount_total','chaoshi_total','sanfang_total','zujin_total1','zujin_total2', 'month_order','ddz_total','ddz_total1','ddz_total2','drz_total','drz_total1','drz_total2','yrz_total','yrz_total1','yrz_total2','ddz_count','ddz_count_month','drz_count','yrz_count'));
            }else{
                if($request->filled('is_reconciliation')){
                    $model = $model->whereIn('is_reconciliation',$request->is_reconciliation);
                }
                // 入账管理用is_reconciliation_time排序
                if(in_array(1,$request->is_reconciliation)){
                    $data = $model->paginate($size);
                }else{
                    $data = $model->orderBy('is_reconciliation_time', 'desc')->paginate($size);
                }
                // 计算合并后的数据的总金额
                if($request->filled('department')){
                    $model2 = $model2->where('department',$request->department);
                }

                // 订单来源
                if($request->filled('order_source')){
                    $model2 = $model2->whereIn('source',$request->order_source);
                }
                if($request->filled('start')&&$request->filled('end')){
                    $model2 = $model2->whereBetween('fact_return_over_at',[$request->start,$request->end]);
                }
                if($request->filled('is_start')&&$request->filled('is_end')){
                    $model2 = $model2->whereBetween('is_reconciliation_time',[$request->is_start,$request->is_end]);
                }
                if($request->filled('ok_start')&&$request->filled('ok_end')){
                    $model2 = $model2->whereBetween('ok_reconciliation_time',[$request->ok_start,$request->ok_end]);
                }
                $model3 = clone $model2;
                $model4 = clone $model2;
                $model5 = clone $model2;
                $model3qu = $model3->where('is_reconciliation', 1)->get();
                $model4qu = $model4->where('is_reconciliation', 2)->get();
                $model5qu = $model5->where('is_reconciliation', 3)->get();
                $ddz_total = $model3qu->sum('fact_pay');
                $ddz_total1 = $model3qu->sum(function ($product) {
                    return empty($product['platform_fact_pay'])?0:$product['platform_fact_pay'];
                });
                $ddz_total2 = $model3qu->sum(function ($product) {
                    return empty($product['over_time_fee'])?0:$product['over_time_fee'];
                });
                $ddz_count = $model3qu->count();
                $ddz_count_month = $model3->where('is_reconciliation', 1)->whereBetween('updated_at', [$startOfMonth, $endOfMonth])->count();
                $drz_total = $model4qu->sum('fact_pay');
                $drz_total1 = $model4qu->sum(function ($product) {
                    return empty($product['platform_fact_pay'])?0:$product['platform_fact_pay'];
                });
                $drz_total2 = $model4qu->sum(function ($product) {
                    return empty($product['over_time_fee'])?0:$product['over_time_fee'];
                });
                $drz_count = $model4qu->count();
                $yrz_total = $model5qu->sum('fact_pay');
                $yrz_total1 = $model5qu->sum(function ($product) {
                    return empty($product['platform_fact_pay'])?0:$product['platform_fact_pay'];
                });
                $yrz_total2 = $model5qu->sum(function ($product) {
                    return empty($product['over_time_fee'])?0:$product['over_time_fee'];
                });
                $yrz_count = $model5qu->count();
                if($request->filled('is_reconciliation')){
                    $model2 = $model2->whereIn('is_reconciliation',$request->is_reconciliation);
                }
                $month_order = $model2->where('status',5)->where('process_status',2)->where('pre_lease_days','>=',30)->whereRaw("DATEDIFF(NOW(), STR_TO_DATE(pre_fetch_time, '%Y-%m-%d')) >= 30")->count();
                $amount_total = $model->sum('fact_pay');
                // 超时费
                // $chaoshi_total = 0;
                // 租金
                $zujin_total1 = 0;
                $zujin_total2 = 0;
                // 超时费
                $chaoshi_total = $model->get()->sum(function ($product) {
                    return empty($product['over_time_fee'])?0:$product['over_time_fee'];
                });
                // 三方平台
                $sanfang_total = $model->get()->sum(function ($product) {
                    return empty($product['platform_fact_pay'])?0:$product['platform_fact_pay'];
                });
                // // 租金
                // $zujin_total1 = $model->sum(function ($product) {
                //     return empty($product['all_handel_amount'])?0:$product['all_handel_amount'];
                // });
                // $zujin_total2 = $model->sum(function ($product) {
                //     return empty($product['settle_lease_price'])?0:$product['settle_lease_price'];
                // });
                return $this->success(compact('data','amount_total','chaoshi_total','sanfang_total','zujin_total1','zujin_total2', 'month_order','ddz_total','ddz_total1','ddz_total2','drz_total','drz_total1','drz_total2','yrz_total','yrz_total1','yrz_total2','ddz_count','ddz_count_month','drz_count','yrz_count'));

            }
        }else{
           // ->select('order_sn','activity_type','source','zujin_income','is_reconcile','additional_services_price','fact_pay_total');
           // 传入order_source时，不查询外调单数据
           if(!$request->filled('order_source') && !$request->filled('nowd')){
                $firstCollect = DB::table('external_transfers')
                ->select(
                    DB::raw('id'),
                    DB::raw('order_sn'),
                    DB::raw('10 as activity_type'),
                    DB::raw('1 as source'),
                    DB::raw('50 as total'),
                    DB::raw('40 as is_reconcile'),
                    DB::raw('30 as additional_services_price'),
                    DB::raw('lease_price as fact_pay_total'),
                    DB::raw('90 as zujin_income'),
                    DB::raw('60 as additional_income'),
                    DB::raw('70 as services_income'),
                    DB::raw('is_reconciliation'),
                    DB::raw('0 as over_time_fee'),
                    DB::raw('profit_price as fact_pay'),
                    DB::raw('department'),
                    DB::raw('category as name'),
                    DB::raw('customer_name as wx_name'),
                    DB::raw('100 as lease_days'),
                    DB::raw('110 as fetch_hours'),
                    DB::raw('start_date as pre_fetch_time'),
                    DB::raw('end_date as pre_return_time'),
                    DB::raw('0 as platform_fact_pay'),
                    DB::raw('3 as settle_status'),
                    DB::raw('lease_price as all_handel_amount'),
                    DB::raw('sd_time as fetch_time'),
                    DB::raw('qh_time as return_time'),
                    DB::raw('plate_number'),
                    DB::raw('0 as diff_rate'),
                    DB::raw('0 as change_price'),
                    DB::raw('0 as settle_lease_price'),
                    DB::raw('is_reconciliation_time'),
                    DB::raw('ok_reconciliation_time'),
                    DB::raw('0 as ok_reconciliation_time'),
                    DB::raw('0 as car_series_id'),
                    DB::raw('0 as is_evidence'),
                );
                if($request->filled('start')&&$request->filled('end')){
                    $firstCollect = $firstCollect->whereBetween('created_at',[$request->start,$request->end]);
                }
                if($request->filled('is_start')&&$request->filled('is_end')){
                    $firstCollect = $firstCollect->whereBetween('is_reconciliation_time',[$request->is_start,$request->is_end]);
                }
                if($request->filled('ok_start')&&$request->filled('ok_end')){
                    $firstCollect = $firstCollect->whereBetween('ok_reconciliation_time',[$request->ok_start,$request->ok_end]);
                }
                if($request->filled('departmentname')){
                    $firstCollect = $firstCollect->where('department',$request->departmentname);
                }
                if($request->filled('order_sns')){
                    $firstCollect = $firstCollect->whereIn('order_sn',$request->order_sns);
                }
                if($request->filled('is_reconciliation')){
                    $firstCollect2 = clone $firstCollect;
                    $model0 = clone $model;
                    $mergedQuery2 = $model0->union($firstCollect2);
                    $mergedResults2 = $mergedQuery2->get();
                    $model3 = clone $mergedResults2;
                    $model4 = clone $mergedResults2;
                    $model5 = clone $mergedResults2;
                    $firstCollect = $firstCollect->whereIn('is_reconciliation',$request->is_reconciliation);
                    $model = $model->whereIn('is_reconciliation',$request->is_reconciliation);
                    // 使用 union 合并两个查询
                    $mergedQuery = $model->union($firstCollect);
                    // 获取合并后的结果
                    if(in_array(1,$request->is_reconciliation)){
                        $mergedResults = $mergedQuery->get();
                    }else{
                        $mergedResults = $mergedQuery->orderBy('is_reconciliation_time', 'desc')->get();
                    }
                }else{
                    // 使用 union 合并两个查询
                    $mergedQuery = $model->union($firstCollect);
                    // 获取合并后的结果
                    if(in_array(1,$request->is_reconciliation)){
                        $mergedResults = $mergedQuery->get();
                    }else{
                        $mergedResults = $mergedQuery->orderBy('is_reconciliation_time', 'desc')->get();
                    }
                    $model3 = clone $mergedResults;
                    $model4 = clone $mergedResults;
                    $model5 = clone $mergedResults;
                }
                $ddz_total = $model3->where('is_reconciliation', 1)->sum('fact_pay');
                $ddz_total1 = $model3->where('is_reconciliation', 1)->sum(function ($product) {
                    return empty($product['platform_fact_pay'])?0:$product['platform_fact_pay'];
                });
                $ddz_total2 = $model3->where('is_reconciliation', 1)->sum(function ($product) {
                    return empty($product['over_time_fee'])?0:$product['over_time_fee'];
                });
                $ddz_count = $model3->where('is_reconciliation', 1)->count();
                $ddz_count_month = $model3->where('is_reconciliation', 1)->whereBetween('updated_at', [$startOfMonth, $endOfMonth])->count();
                $drz_total = $model4->where('is_reconciliation', 2)->sum('fact_pay');
                $drz_total1 = $model4->where('is_reconciliation', 2)->sum(function ($product) {
                    return empty($product['platform_fact_pay'])?0:$product['platform_fact_pay'];
                });
                $drz_total2 = $model4->where('is_reconciliation', 2)->sum(function ($product) {
                    return empty($product['over_time_fee'])?0:$product['over_time_fee'];
                });
                $drz_count = $model4->where('is_reconciliation', 2)->count();
                $yrz_total = $model5->where('is_reconciliation', 3)->sum('fact_pay');
                $yrz_total1 = $model5->where('is_reconciliation', 3)->sum(function ($product) {
                    return empty($product['platform_fact_pay'])?0:$product['platform_fact_pay'];
                });
                $yrz_total2 = $model5->where('is_reconciliation', 3)->sum(function ($product) {
                    return empty($product['over_time_fee'])?0:$product['over_time_fee'];
                });
                $yrz_count = $model5->where('is_reconciliation', 3)->count();
            } else {
                $model3 = clone $model;
                $model4 = clone $model;
                $model5 = clone $model;
                $model3qu = $model3->where('is_reconciliation', 1)->get();
                $model4qu = $model4->where('is_reconciliation', 2)->get();
                $model5qu = $model5->where('is_reconciliation', 3)->get();
                if($request->filled('is_reconciliation')){
                    $model = $model->whereIn('is_reconciliation',$request->is_reconciliation);
                }

                if(in_array(1,$request->is_reconciliation)){
                    $mergedResults = $model->get();
                }else{
                    $mergedResults = $model->orderBy('is_reconciliation_time', 'desc')->get();
                }
                $ddz_total = $model3qu->sum('fact_pay');
                $ddz_total1 = $model3qu->sum(function ($product) {
                    return empty($product['platform_fact_pay'])?0:$product['platform_fact_pay'];
                });
                $ddz_total2 = $model3qu->sum(function ($product) {
                    return empty($product['over_time_fee'])?0:$product['over_time_fee'];
                });
                $ddz_count = $model3qu->count();
                $ddz_count_month = $model3->where('is_reconciliation', 1)->whereBetween('updated_at', [$startOfMonth, $endOfMonth])->count();
                $drz_total = $model4qu->sum('fact_pay');
                $drz_total1 = $model4qu->sum(function ($product) {
                    return empty($product['platform_fact_pay'])?0:$product['platform_fact_pay'];
                });
                $drz_total2 = $model4qu->sum(function ($product) {
                    return empty($product['over_time_fee'])?0:$product['over_time_fee'];
                });
                $drz_count = $model4qu->count();
                $yrz_total = $model5qu->sum('fact_pay');
                $yrz_total1 = $model5qu->sum(function ($product) {
                    return empty($product['platform_fact_pay'])?0:$product['platform_fact_pay'];
                });
                $yrz_total2 = $model5qu->sum(function ($product) {
                    return empty($product['over_time_fee'])?0:$product['over_time_fee'];
                });
                $yrz_count = $model5qu->count();
            }
            // 计算合并后的数据的总金额
            $amount_total = $mergedResults->sum('fact_pay');
            // 超时费
            $chaoshi_total = $mergedResults->sum(function ($product) {
                return empty($product['over_time_fee'])?0:$product['over_time_fee'];
            });
            // 三方平台
            $sanfang_total = $mergedResults->sum(function ($product) {
                return empty($product['platform_fact_pay'])?0:$product['platform_fact_pay'];
            });
            // // 租金
            // $zujin_total1 = $mergedResults->sum(function ($product) {
            //     return empty($product['all_handel_amount'])?0:$product['all_handel_amount'];
            // });
            // $zujin_total2 = $mergedResults->sum(function ($product) {
            //     return empty($product['settle_lease_price'])?0:$product['settle_lease_price'];
            // });
            // 超时费
            // $chaoshi_total = 0;
            // 租金
            $zujin_total1 = 0;
            $zujin_total2 = 0;
            // 对数据进行分页
            $perPage = $size;
            $page = request()->get('page', 1);
            // 将结果转换为集合
            $collection = collect($mergedResults);

            // 手动分页
            // LengthAwarePaginator::
            $data = new LengthAwarePaginator(
                $collection->forPage($page, $perPage),
                $collection->count(),
                $perPage,
                $page,
                ['path' => request()->url(), 'query' => request()->query()]
            );
            if($request->filled('department')){
                $model2 = $model2->where('department',$request->department);
            }

            // 订单来源
            if($request->filled('order_source')){
                $model2 = $model2->whereIn('source',$request->order_source);
            }
            if($request->filled('start')&&$request->filled('end')){
                $model2 = $model2->whereBetween('fact_return_over_at',[$request->start,$request->end]);
            }
            if($request->filled('is_start')&&$request->filled('is_end')){
                $model2 = $model2->whereBetween('is_reconciliation_time',[$request->is_start,$request->is_end]);
            }
            if($request->filled('ok_start')&&$request->filled('ok_end')){
                $model2 = $model2->whereBetween('ok_reconciliation_time',[$request->ok_start,$request->ok_end]);
            }
            if($request->filled('is_reconciliation')){
                $model2 = $model2->whereIn('is_reconciliation',$request->is_reconciliation);
            }
            $month_order = $model2->where('status',5)->where('process_status',2)->where('pre_lease_days','>=',30)->whereRaw("DATEDIFF(NOW(), STR_TO_DATE(pre_fetch_time, '%Y-%m-%d')) >= 30")->count();
            return $this->success(compact('data','amount_total','chaoshi_total','sanfang_total','zujin_total1','zujin_total2','month_order','ddz_total','ddz_total1','ddz_total2','drz_total','drz_total1','drz_total2','yrz_total','yrz_total1','yrz_total2','ddz_count','ddz_count_month','drz_count','yrz_count'));
        }
    }
    public function getIncomeMonth(CarOrder $model,Request $request){
        // 月账单拆分（原始需求：月租订单变更：月租即租车时长超过30个自然日的订单，若没有操作结算，那么在超过30个自然日的当月，租金统计的月账单中需要出现，可以操作对账。区别于之前已结算才能对账的逻辑。）
        // 逻辑整理:待取回的订单里，还车时间在当前时间之前的且租车时长超过30个自然日的，且没有结算，需要存到订单月订单子表里单独管理；
        // 找到符合条件的订单
        $size = $request->input('size',10);
        $model = $model
        ->where('status',5)
        ->where('process_status',2)
        ->where('pre_lease_days','>=',30)
        ->whereRaw("DATEDIFF(NOW(), STR_TO_DATE(pre_fetch_time, '%Y-%m-%d')) >= 30")
        ->select('id','order_sn','activity_type','source','total','is_reconcile','additional_services_price','fact_pay_total','zujin_income','additional_income','services_income', 'is_reconciliation', 'over_time_fee','fact_pay', 'department', 'name', 'wx_name', 'lease_days', 'fetch_hours', 'pre_fetch_time', 'pre_return_time', 'platform_fact_pay', 'settle_status', 'all_handel_amount', 'fetch_time' ,'return_time', 'plate_number','diff_rate','change_price','settle_lease_price','is_reconciliation_time','ok_reconciliation_time','mini_phone','car_series_id','is_evidence');
        if($request->filled('department')){
            $model = $model->where('department',$request->department);
        }
        // 订单来源
        if($request->filled('order_source')){
            $model = $model->whereIn('source',$request->order_source);
        }
        if($request->filled('start')&&$request->filled('end')){
            $model = $model->whereBetween('created_at',[$request->start,$request->end]);
        }
        $month_order = $model->count();
        $data = $model->paginate($size);
        return $this->success(compact('data','month_order'));
    }
    // 刮擦收入
    public function getScratch(CarOrder $model,Request $request){
        $size = $request->input('size',10);
        $model = $model
        ->where('status',6)
        ->where('scratch_fee','>',0)
        ->whereIn('process_status',[4,5,6])
        ->select('id','order_sn','activity_type','source','total','is_reconcile','additional_services_price','fact_pay_total','zujin_income','additional_income','services_income', 'is_reconciliation', 'over_time_fee','fact_pay', 'scratch_fee', 'department', 'name', 'wx_name', 'lease_days', 'fetch_hours', 'pre_fetch_time', 'pre_return_time', 'platform_fact_pay', 'settle_status', 'all_handel_amount', 'fetch_time' ,'return_time', 'plate_number','diff_rate','change_price','settle_lease_price','is_reconciliation_time','ok_reconciliation_time','mini_phone','car_series_id','is_evidence');

        if($request->filled('department')){
            $model = $model->where('department',$request->department);
        }

        // 订单来源
        if($request->filled('order_source')){
            $model = $model->whereIn('source',$request->order_source);
        }
        if($request->filled('start')&&$request->filled('end')){
            $model = $model->whereBetween('created_at',[$request->start,$request->end]);
        }
        $data = $model->paginate($size);
        $amount_total = $model->sum('scratch_fee');
        return $this->success(compact('data','amount_total'));
    }
    // 事故维修
    public function accendent(Service $model,Request $request){
        $size = $request->input('size',10);
        if($request->filled('department_id')){
            $model = $model->where('department_id',$request->department_id);
        }
        $model = $model->where('is_custom',4)->where('status',4)->with('customer');
        $data = $model->paginate($size);
        $productsCollection = $data->getCollection();
        $insurance_float = $productsCollection->sum('insurance_float'); // 上浮金汇总
        $depreciation = $productsCollection->sum('depreciation'); // 折旧汇总
        $commission = $productsCollection->sum('commission'); // 返点汇总
        $contents_price = $productsCollection->sum('contents_price'); // 维修总额
        $amount_total = round($insurance_float+$depreciation+$commission-$contents_price,2); // 收入=上浮金+折旧+返点-维修总额
        return $this->success(compact('amount_total','data'));
    }
//    车辆维修支付
    public function payService(Service $model,Request $request){
        $size = $request->input('size',20);
        if($request->filled('start')&&$request->filled('end')){
            $model = $model->whereBetween('end',[$request->start,$request->end]);
        }
        if($request->filled('address')){
            $model = $model->where('address','like','%'.$request->address.'%');
        }
        if($request->filled('contents')){
            $model = $model->where('contents','like','%'.$request->contents.'%');
        }
        if($request->filled('plate_number')){
            $model = $model->where('plate_number','like','%'.$request->plate_number.'%');
        }
        if($request->filled('car_series_name')){
            $model = $model->where('car_series_name','like','%'.$request->car_series_name.'%');
        }
        $model = $model->where('status',4);
        $data = $model->paginate($size);
        $productsCollection = $data->getCollection();
        $amount_total = $productsCollection->sum('repair_price');
        $count = $productsCollection->count();
        return $this->success(compact('amount_total','count','data'));
    }

    // 违章支出
    public function illegals(Illegal $model,Request $request){
        $size = $request->input('size',10);
        $model = $model->select('created_at','amount','contents');
        if($request->filled('start')&&$request->filled('end')){
            $model = $model->whereBetween('created_at',[$request->start,$request->end]);
        }
        $model = $model->paginate($size);
        return $this->success($model);
    }
    // 保养
    public function maintenance(Maintenance $model, Request $request){
        $size = $request->input('size',20);
        if($request->filled('start')&&$request->filled('end')){
            $model = $model->whereBetween('created_at',[$request->start,$request->end]);
        }
        if($request->filled('address')){
            $model = $model->where('address','like','%'.$request->address.'%');
        }
        // contents
        if($request->filled('contents')){
            $model = $model->where('contents','like','%'.$request->contents.'%');
        }
        //car_series_name
        if($request->filled('car_series_name')){
            $model = $model->where('car_series_name','like','%'.$request->car_series_name.'%');
        }
        // plate_number
        if($request->filled('plate_number')){
            $model = $model->where('plate_number','like','%'.$request->plate_number.'%');
        }
        $model = $model->select('created_at','car_series_name','plate_number','start','end','contents','address','images','price','amount_total');
        $data = $model->paginate($size);
        $productsCollection = $data->getCollection();
        $amount_total = $productsCollection->sum('amount_total');
        $count = $productsCollection->count();
        return $this->success(compact('amount_total','count','data'));
    }
    // 保险
    public function insure(InsureLogs $model, Request  $request){
        $size = $request->input('size');
        if($request->filled('start')&&$request->filled('end')){
            $model = $model->whereBetween('created_at',[$request->start,$request->end]);
        }
        if($request->filled('company_name')){
            $model = $model->where('company_name','like','%'.$request->company_name.'%');
        }
        $model = $model->with('car')->select('car_id','insurance_premium','company_name','vci_fee','tci_fee','pdf1','pdf2');
        $data = $model->paginate($size);
        $productsCollection = $data->getCollection();
        $price = $productsCollection->sum('insurance_premium');
        return $this->success(compact('price','data'));

    }
    // 利息支出
    public function interest(MortgageLog $model,Request $request){
        $size = $request->input('size',20);
        $model = $model->select('order_sn','plate_numbers','total_number','mortgage_amount','interest');
        $model = $model->where('status',2);
        $data = $model->paginate($size);
        $totalsum = $model->selectRaw('sum(interest) as mount_all')->first();
        $amount_all = $totalsum->mount_all;
        return $this->success(compact('data','amount_all'));
    }
    // 营销统计
    public function markerExpense(MarketExpense $model,Request  $request){
        $size = $request->input('size');
        if($request->filled('start')&&$request->filled('end')){
            $model = $model->whereBetween('created_at',[$request->start,$request->end]);
        }
        if($request->filled('plateform_name')){
            $model = $model->where('plateform_name','like','%'.$request->plateform_name.'%');
        }
        $data = $model->paginate($size);
        return $this->success($data);
    }
    // 残值统计
    public function residualValue(RecognizeDrivingLicense $model, Request $request){
        $size = $request->input('size',20);
        $data = $model->query()->with('residual')->onlyTrashed()->paginate($size);
        return $this->success(compact('data'));
    }
    // 车辆出租率
    public function attendance(RecognizeDrivingLicense $model, Request $request){
        $size = $request->input('size',20);
        $model = $model->with('renews')->select('gear_car_name','id','plate_number','category');

        // if($request->filled('start')&&$request->filled('end')){
        //     $model = $model->whereBetween('updated_at',[$request->start,$request->end]);
        // }
        if($request->filled('plateform_name')){
            if(is_array($request->plateform_name)){
                $arr = $request->plateform_name;
            }else{
                $arr = json_decode($request->plateform_name,true);
            }
            $model = $model->whereIn('plateform_name',$arr);
        }
        if($request->filled('car_series_id')){
            if(is_array($request->car_series_id)){
                $arr = $request->car_series_id;
            }else{
                $arr = json_decode($request->car_series_id,true);
            }
            $model = $model->whereIn('car_series_id',$arr);
        }
        if($request->filled('plate_numbers')){
            if(is_array($request->plate_numbers)){
                $arr = $request->plate_numbers;
            }else{
                $arr = json_decode($request->plate_numbers,true);
            }
            $model = $model->whereIn('plate_number',$arr);
        }
        if($request->filled('lease_times')){
            if($request->lease_times==1){
                $model->orderBy('lease_times','asc');
            }else{
                $model->orderBy('lease_times','desc');
            }
        }
        if($request->filled('total_lease_amount')){
            if($request->total_lease_amount==1){
                $model->orderBy('total_lease_amount','desc');
            }else{
                $model->orderBy('total_lease_amount','desc');
            }
        }
//        $model = $model->with('residual');
        $model = $model->withCount(['orders'=>function($query)use($request){
            if($request->filled('start')&&$request->filled('end')){
                $query->where('process_status',6)->whereBetween('pre_fetch_time',[$request->start,$request->end]);
            } else {
                $query->where('process_status',6);
            }
        }]);
        $model = $model->withCount(['orders'=>function($query)use($request){
            if($request->filled('start')&&$request->filled('end')){
                $query->where('process_status',6)->whereBetween('pre_fetch_time',[$request->start,$request->end]);
            } else {
                $query->where('process_status',6);
            }
        }],'renews');
        $model = $model->withSum(['orders'=>function($query)use($request){
            if($request->filled('start')&&$request->filled('end')){
                $query->where('process_status',6)->whereBetween('pre_fetch_time',[$request->start,$request->end]);
            } else {
                $query->where('process_status',6);
            }
        }],'zujin_income');
        $model = $model->withSum(['orders'=>function($query)use($request){
            if($request->filled('start')&&$request->filled('end')){
                $query->where('process_status',6)->whereBetween('pre_fetch_time',[$request->start,$request->end]);
            } else {
                $query->where('process_status',6);
            }
        }],'lease_days');
        $data = $model->paginate($size);
        return $this->success($data);
    }
    public function userAddStatistics(Request $request,Customer $model){
        $size = $request->input('size',20);
    // 获取本月的开始和结束日期
        $start = $request->input('start_month',Carbon::now()->month);
        $end = $request->input('end_month',Carbon::now()->subMonth()->month);
        $startYear = $request->input('start_year',Carbon::now()->year);
        $endYear = $request->input('end_year',Carbon::now()->year);

        $startMonth = Carbon::create($startYear, $start, 1)->startOfMonth();
        $endMonth = Carbon::create($startYear, $start, 1)->endOfMonth();

        $startMonthData = $this->getMonthTotal($startMonth,$endMonth,0);

        $finishStartMonth = Carbon::create($endYear, $end, 1)->startOfMonth();
        $finishMonth = Carbon::create($endYear, $end, 1)->endOfMonth();

        $endMonthData = $this->getMonthTotal($finishStartMonth,$finishMonth,0);
        $today = Customer::query()
            ->where('is_black',0)
            ->whereBetween('created_at',[Carbon::today()->startOfDay(),Carbon::today()->endOfDay()])->count();
        if($request->filled('start')&&$request->filled('end')){
            $model = $model->whereBetween('created_at',[$request->start,$request->end]);
        }
        if($request->filled('department_id')){
            $model = $model->where('department_id',$request->department_id);
            $thisData = $this->getMonthTotal($request->start,$request->end,$request->department_id);
        }else{
            $thisData = $this->getMonthTotal($request->start,$request->end,0);
        }
        if($request->filled('source')){
            $model = $model->whereIn('source',$request->source);
        }
        $model = $model->select('created_at','name','phone','department_id','source','vehicle_type','lease_days','is_deposit_free','mount_all')
            ->with(['departments'=>function($query){
                $query->select('id','name');
            }]);
        $data = $model->paginate($size);
        return $this->success(compact('startMonthData','endMonthData','thisData','today','data'));
    }
    protected function diffDays($start, $end){
        $days = Carbon::parse($start)->diffInDays(Carbon::parse($end));
        $second = $this->diffSeconds($end, $start);
        if($second<3600 * 6){
            return 1;
        }else{
            $day = 3600 * 24 * $days;
            $second = $second - $day;
            if ($second >= 3600 * 6) {
                return $days + 1;
            }else {
                return $days;
            }
        }
    }
    protected function diffSeconds($end, $sta)
    {
        return strtotime($end) - strtotime($sta);
    }
    protected function getMonthTotal($start,$end,$department_id){
        if($department_id!=0){
            // 获取免押金
            $isDepositFree = Customer::query()
                ->where('is_deposit_free', 2)
                ->where('is_black',0)
                ->where('department_id',$department_id)
                ->whereBetween('created_at',[$start,$end])->count();
             // 获取来源
             $arr = [
                 '其他','58','百度','抖音','美团','地图','转介绍门店','微信小程序',
                 '携程','悟空','哈罗','飞猪','联动云'
             ];
             $channel = [];
             foreach ($arr as $key=>$value){
                 $channel[$key]['label'] = $value;
                 $channel[$key]['value'] = Customer::query()
                     ->where('source', $value)
                     ->where('is_black',0)
                     ->where('department_id',$department_id)
                     ->whereBetween('created_at',[$start,$end])->count();
             }
            $total =  Customer::query()->where('is_black',0)->where('department_id',$department_id)->whereBetween('created_at',[$start,$end])->count();
        }else{
            // 获取免押金
            $isDepositFree = Customer::query()
                ->where('is_deposit_free', 2)
                ->where('is_black',0)
                ->whereBetween('created_at',[$start,$end])->count();
             // 获取来源
             $arr = [
                 '其他','58','百度','抖音','美团','地图','转介绍门店','微信小程序',
                 '携程','悟空','哈罗','飞猪','联动云'
             ];
             $channel = [];
             foreach ($arr as $key=>$value){
                 $channel[$key]['label'] = $value;
                 $channel[$key]['value'] = Customer::query()
                     ->where('source', $value)
                     ->where('is_black',0)
                     ->whereBetween('created_at',[$start,$end])->count();
             }
            $total =  Customer::query()->where('is_black',0)->whereBetween('created_at',[$start,$end])->count();
        }
        return compact('isDepositFree','total','channel');
    }
    public function changeOrderLog(LeaseChangeLog $model, Request $request){
        $size = $request->input('size',10);
        $data = $model->query()
            ->with(['company'=>function($query){
                $query->select('id','name');
            }])
            ->where('id','>',0)->orderBy('id','desc')->paginate($size);
        return $this->success($data);
    }
    // 看板统计
    public function orderStaticstics(RecognizeDrivingLicense $model, Request $request){

        // 所有车辆
        $allCars = RecognizeDrivingLicense::query()->get();
        // 今日回车的订单
        $todayReturnOrders = CarOrder::query()->whereBetween('pre_return_time',[now()->startOfDay(),now()->endOfDay()])->get();
        // 今日新增车辆
        $todayAdd = RecognizeDrivingLicense::query()->whereBetween('created_at',[now()->startOfDay(),now()->endOfDay()])->count('id');
        // 今日维修中
        $todayService = $allCars->whereIn('repair_status',[2,3,4])->count();
        // 今日空闲
        $todayWaitLease = $allCars->where('is_used',0)->count();
        // 今日在租
        $todaySend = $allCars->where('is_used','!=',0)->count();
        // 今日回车中
        $todayReceive = $todayReturnOrders->count();
        // 月租统计--按预时长天数字段pre_lease_days来计算
        $orders = CarOrder::query()->where('pre_lease_days', '<=', 30);
        if($request->filled('start')&&$request->filled('end')){
            $orders = $orders->whereBetween('created_at',[$request->start,$request->end]);
        }

        $orders = $orders->get();
        $oneDayOrders = $orders->where('pre_lease_days',1)->count();
        $twoDayOrders = $orders->where('pre_lease_days','<=',2)->count();
        $threeDayOrders = $orders->where('pre_lease_days','<=',3)->count();
        $fiveDayOrders = $orders->where('pre_lease_days','<=',5)->count();
        $thirtyDayOrders = $orders->count();

        return $this->success(compact('todayAdd','todayReceive','todayService',
            'todaySend','todayWaitLease','oneDayOrders','twoDayOrders','threeDayOrders',
        'fiveDayOrders','thirtyDayOrders'));
    }
    // 营收表统计
    // public function revenueStatement(CarOrder $model,Request $request){
    //     if($request->filled('start')&&$request->filled('end')){
    //         $startOfYear = $request->start;
    //         $endOfYear = $request->end;
    //     }else{
    //         // 获取当前年份的起点和终点
    //         $startOfYear = Carbon::now()->startOfYear();
    //         $endOfYear = Carbon::now()->endOfYear();
    //     }
    //    $monthlyOrders = $model->query()->selectRaw('MONTH(created_at) as month, COUNT() as total_orders')
    //        ->whereBetween('created_at', [$startOfYear, $endOfYear])
    //        ->groupBy(DB::raw('MONTH(created_at)'))
    //        ->get();
    // }
    // 营收统计
    public function OrderRevenueStatement(RevenueStatement $model,Request $request){
        $dataaa = $model->query()->get();
        return $this->success($dataaa);
    }
    // 手动同步营收信息
    public function asyncRevenueStatement(Request $request){
        // 取出所有已结算订单
        $ordersett = CarOrder::query()->where('status', 6)->whereIn('process_status',[4,5,6])->where('fact_pay','>', 0)->select('department','created_at', 'fact_pay')->get()->toArray();
        // 取出外调订单
        $firstCollect = ExternalTransfer::query()->select(
                        DB::raw('department_id as department'),
                        DB::raw('created_at'),
                        DB::raw('profit_price as fact_pay'),
                    )->get()->toArray();
        $ordersettdate = [];
        for ($i=0; $i < count($ordersett); $i++) {
            $date = Carbon::parse($ordersett[$i]['created_at']);
            $ordersett[$i]['year'] = $date->year;
            $ordersett[$i]['month'] = $date->month;
            $ordersettdate[] = [
                    'department'=>$ordersett[$i]['department'],
                    'fact_pay'=>0,
                    'month'=>$ordersett[$i]['month'],
                    'year'=>$ordersett[$i]['year'],
                    'keys'=>$ordersett[$i]['department'] . $ordersett[$i]['year'] . $ordersett[$i]['month']
            ];
        }
        for ($o=0; $o < count($firstCollect); $o++) {
            $date = Carbon::parse($firstCollect[$o]['created_at']);
            $firstCollect[$o]['year'] = $date->year;
            $firstCollect[$o]['month'] = $date->month;
            $ordersettdate[] = [
                    'department'=>$firstCollect[$o]['department'],
                    'fact_pay'=>0,
                    'month'=>$firstCollect[$o]['month'],
                    'year'=>$firstCollect[$o]['year'],
                    'keys'=>$firstCollect[$o]['department'] . $firstCollect[$o]['year'] . $firstCollect[$o]['month']
            ];
        }
        $collection = collect($ordersettdate);
        $uniquelist = $collection->unique('keys')->values()->all();
        for ($j=0; $j < count($ordersett); $j++) {
            $keys = $ordersett[$j]['department'] . $ordersett[$j]['year'] . $ordersett[$j]['month'];
            $index = array_search($keys, array_column($uniquelist, 'keys'));
            $uniquelist[$index]['fact_pay'] = $uniquelist[$index]['fact_pay']+$ordersett[$j]['fact_pay'];
        }
        for ($p=0; $p < count($firstCollect); $p++) {
            $keys = $firstCollect[$p]['department'] . $firstCollect[$p]['year'] . $firstCollect[$p]['month'];
            $index = array_search($keys, array_column($uniquelist, 'keys'));
            $uniquelist[$index]['fact_pay'] = $uniquelist[$index]['fact_pay']+$firstCollect[$p]['fact_pay'];
        }
        for ($n=0; $n < count($uniquelist); $n++) {
            // 更新到营收表（实收租金：fact_pay）
            RevenueStatement::query()->where('department_id', $uniquelist[$n]['department'])->where('year', $uniquelist[$n]['year'])->where('month', $uniquelist[$n]['month'])->update(['income'=>$uniquelist[$n]['fact_pay']]);
        }
        return $this->success($uniquelist);
    }
    // 获取车系名称和车牌号
    public function getSelectCarName(){
        $orders = Car::query()
            ->select('id','name', 'total_price', 'category')

            ->where('id','>',0)
            ->get();
        $seriesName = $orders->map(function ($order) {
            return collect($order)->except(['gear_car_num', 'empty_number']);
        });
        $plateName = RecognizeDrivingLicense::query()
            ->select('id','plate_number','car_series_id')
            ->where('id','>',0)->get();
        return $this->success(compact('seriesName','plateName'));
    }
}
